<template>
  <div>
    <VantNavigationBar title="搜索"></VantNavigationBar>
    <van-search
      v-model="Searchvalue.search_name"
      show-action
      background="#76AA28"
      placeholder="请输入搜索关键词"
    >
      <template #action>
        <div @click="onClickButton">搜索</div>
      </template>
    </van-search>
    <div v-if="SearchResults.length === 0">
      <div
        v-for="history in historyList"
        :key="history.history_id"
        :value="history.history_content"
        class="history"
      >
        {{ history.history_content }}
      </div>
    </div>
    <div>
      <van-card
        v-for="Result in SearchResults"
        :key="Result.product_id"
        :price="Result.product_price"
        :desc="Result.product_dsc"
        :title="Result.product_name"
        :thumb="'http://localhost:8090/' + Result.product_imge"
        @click="goInfo(Result.product_id)"
      />
    </div>
  </div>
</template>
<script>
import { Col, Row, Icon, Search, showToast, Card } from 'vant'
import { ref } from 'vue'
import VantNavigationBar from '@/components/Navbar'
import home from '@/api/home'
import { useRouter } from 'vue-router'

export default {
  components: {
    VantNavigationBar,
    [Col.name]: Col,
    [Row.name]: Row,
    [Icon.name]: Icon,
    [Search.name]: Search,
    [showToast.name]: showToast,
    [Card.name]: Card,
  },
  setup() {
    const Searchvalue = ref({
      search_name: '',
    })
    const historyList = ref([])
    const SearchResults = ref([])
    const router = useRouter()
    const onClickButton = () => {
      if (!Searchvalue.value.search_name) {
        showToast('请输入关键词！')
        return
      }
      home.fuzzySearch(Searchvalue.value).then((res) => {
        if (res.status === 200 && res.data) {
          SearchResults.value = res.data
          home.historySearch(Searchvalue.value)
          refreshHistorySearch()
        } else if (res.status === 400) {
          showToast(res.msg)
          home.historySearch(Searchvalue.value)
        }
      })
    }

    // 定义函数用于刷新历史搜索列表
    const refreshHistorySearch = () => {
      home.gethistorySearch().then((res) => {
        if (res.status === 200) {
          historyList.value = res.data
        }
      })
    }

    const goInfo = (product_id) => {
      router.push({
        name: 'ProductInfo',
        params: { productId: product_id },
      })
    }
    // 初始化时调用获取历史搜索接口
    refreshHistorySearch()
    return {
      Searchvalue,
      onClickButton,
      historyList,
      refreshHistorySearch,
      SearchResults,
      goInfo,
    }
  },
}
</script>
<style scoped>
.history {
  display: inline-block;
  border: 1px solid #ccc;
  background-color: #ccc;
  border-radius: 5px;
  padding: 2px;
  box-sizing: border-box; /* 使用 border-box 让边框包含在元素的宽度内 */
  margin: 10px; /* 添加一些间距，使得历史记录之间有一定的间隔 */
}
</style>
